<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      </BasicForm>
    </n-card>
    <n-grid class="mt-4" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi :span="leftRow">
        <n-card :bordered="false" class="proCard">
          <BasicTable
              :columns="columns"
              :request="loadDataTable"
              :actionColumn="actionColumn"
              :row-key="(row) => row.id"
              ref="actionRef"
              @update:checked-row-keys="onCheckedRow">
            <template #action>
              <TableAction/>
            </template>
          </BasicTable>
        </n-card>
      </n-gi>
      <n-gi :span="3-leftRow">
        <n-card :segmented="{ content: true }" :bordered="false" size="small" closable @close="handleClose">
          <template #header>
            <n-space>
              <n-icon size="18">
                <FormOutlined />
              </n-icon>
              <span>会话详情</span>
            </n-space>
          </template>
          <n-descriptions label-placement="left">
            <n-descriptions-item label="姓名">
              {{ formParams.name }}
            </n-descriptions-item>
            <n-descriptions-item label="部门">
              {{ formParams.dept }}
            </n-descriptions-item>
            <n-descriptions-item label="会话时间">
              {{ formParams.dateTime }}
            </n-descriptions-item>
            <n-descriptions-item label="反馈">
              <n-tag v-if="formParams.feedback >= 2" type="success">
                {{ formParams.feedback === 2 ? '中' : '好'}}
              </n-tag>
              <n-tag v-else type="error">
                {{ formParams.feedback === 1 ? '差' : '未反馈'}}
              </n-tag>
            </n-descriptions-item>
            <n-descriptions-item label="推荐">
              <n-tag v-if="formParams.refer_status" type="success">
                是
              </n-tag>
              <n-tag v-else type="error">
                否
              </n-tag>
            </n-descriptions-item>
          </n-descriptions>
          <n-card :segmented="{ content: true }" :bordered="true" size="small" class="mt-4 min-h-36"
                  style="max-height: 510px; overflow-y: auto">
            <n-skeleton v-if="formParams.loading" text :repeat="10" />
            <n-empty v-else-if="!formParams.chatList || formParams.chatList.length === 0" description="没有会话记录">
            </n-empty>
            <div v-else v-for="(item, index) in formParams.chatList" content-indented>
              <n-thing content-indented class="mt-2">
                <template #avatar>
                  <n-avatar>
                    <n-icon>
                      <user-outlined />
                    </n-icon>
                  </n-avatar>
                </template>
                <template #header>
                  提问
                </template>
                <template #header-extra>
                  <n-button circle size="small">
                    <template #icon>
                      <n-tooltip trigger="hover">
                        <template #trigger>
                          <delete-outlined @click="handleDeleteChat(item,
                          () => formParams.chatList = formParams.chatList.filter((item, i) => i !== index))"/>
                        </template>
                        删除本次问答
                      </n-tooltip>
                    </template>
                  </n-button>
                </template>
                <div style="white-space: pre-wrap" v-html="item.prompt" class="border p-2 rounded-md"></div>
              </n-thing>
              <n-thing content-indented class="mt-2">
                <template #avatar>
                  <n-avatar>
                    <n-icon>
                      <robot-outlined />
                    </n-icon>
                  </n-avatar>
                </template>
                <template #header>
                  回答
                </template>
                <div style="white-space: pre-wrap" v-html="item.text" class="border p-2 rounded-md"></div>
              </n-thing>
            </div>
          </n-card>
        </n-card>
      </n-gi>
    </n-grid>
  </div>
</template>

<script lang="ts" setup>
import {h, inject, reactive, ref, defineComponent, nextTick} from 'vue';
import {NInput, NTag, useDialog, useMessage} from 'naive-ui';
import {BasicTable, TableAction} from '@/components/Table';
import {BasicForm, FormSchema, useForm} from '@/components/Form';
// import {columns} from './columns';
import {useRouter} from 'vue-router';
import {
  deleteConversationChat,
  getChatList,
  getConversationList,
  updateConversation
} from "@/api/chat/history";
import {DeleteOutlined, FormOutlined, RobotOutlined, UserOutlined} from "@vicons/antd";
import {delRefer} from "@/api/chat/refer";

const reloadPage = inject('reloadPage') as Function;

const schemas: FormSchema[] = [
  {
    field: 'name',
    component: 'NInput',
    label: '姓名',
    componentProps: {
      placeholder: '请输入姓名',
      onInput: (e: any) => {
        searchForm.value.name = e;
      },
    },
  },
  {
    field: 'dept',
    component: 'NInput',
    label: '部门',
    componentProps: {
      placeholder: '请输入部门',
      onInput: (e: any) => {
        searchForm.value.dept = e;
      },
    },
  },
  {
    field: 'telephone',
    component: 'NInput',
    label: '手机号',
    componentProps: {
      placeholder: '请输入手机号码',
      onInput: (e: any) => {
        searchForm.value.telephone = e;
      },
    },
  },
  {
    field: 'feedback',
    component: 'NSelect',
    label: '评价',
    componentProps: {
      placeholder: '请选择评价',
      options: [
        {
          label: '未评价',
          value: '0',
        },
        {
          label: '差',
          value: '1',
        },
        {
          label: '中',
          value: '2',
        },
        {
          label: '好',
          value: '3',
        },
      ],
      onUpdateValue: (e: any) => {
        searchForm.value.feedback = e;
      },
    },
  },
];

const router = useRouter();
const message = useMessage();
const actionRef = ref();
const leftRow = ref(3);
const isShowDetail = ref(false);

const formParams = reactive({
  id: '',
  userId: '',
  dept: '',
  name: '',
  telephone: '',
  conversationId: '',
  feedback: 0,
  refer_status: 0,
  dateTime: '',
  loading: false,
  chatList: []
});

const dialog = useDialog();

const defaultValueRef = () => ({
  name: undefined,
  dept: undefined,
  telephone: undefined,
  feedback: undefined,
  refer_status: undefined,
});

const searchForm = ref(defaultValueRef())

const params = reactive({
  pageSize: 10,
});

const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 s:2 s:3 s:4 s:5 s:6' },
  labelWidth: 80,
  showAdvancedButton: false,
  schemas,
});

const loadDataTable = async (params: any) => {
  params = {
    ...params,
    ...searchForm.value,
    refer_status: 1,
  }
  const response = await getConversationList(params)
  return response.data;
};

const ShowOrEdit = defineComponent({
  props: {
    value: [String, Number],
    onUpdateValue: [Function, Array]
  },
  setup (props) {
    const isEdit = ref(false)
    const inputRef = ref(null)
    const inputValue = ref(props.value)
    function handleOnClick () {
      isEdit.value = true
      nextTick(() => {
        inputRef.value.focus()
      })
    }
    function handleChange () {
      isEdit.value = false
      props.onUpdateValue(inputValue.value)
    }
    return () =>
      h(
        'div',
        {
          style: 'min-height: 22px',
          onClick: handleOnClick
        },
        isEdit.value
          ? h(NInput, {
            ref: inputRef,
            value: inputValue.value,
            onUpdateValue: (v) => {
              inputValue.value = v
            },
            onChange: handleChange,
            onBlur: handleChange
          })
          : props.value
      )
  }
})

const columns = reactive([
  {
    type: 'selection',
    disabled (row) {
      return row.refer_status === 1
    }
  },
  {
    title: '姓名',
    key: 'name',
  },
  {
    title: '部门',
    key: 'dept',
  },
  {
    title: '标题',
    key: 'prompt',
    render (row, index) {
      return h(ShowOrEdit, {
        value: row.prompt,
        onUpdateValue (v) {
          const dataSource = actionRef.value.getDataSource()
          if (dataSource) {
            const data = dataSource[index]
            if (data) {
              data.prompt = v
              updateConversation({
                id: data.id,
                prompt: v
              })
            }
          }
        }
      })
    }
  },
  {
    title: '反馈',
    key: 'feedback',
    render(row) {
      return h(
        NTag,
        {
          type: row.feedback >= 2 ? 'success' : 'error',
        },
        {
          default: () => (row.feedback === 1 ? '差' : row.feedback === 2 ? '中' : row.feedback === 3 ? '好' : '未评价'),
        }
      );
    },
  },
  {
    title: '推荐',
    key: 'refer_status',
    render(row) {
      return h(
        NTag,
        {
          type: row.refer_status === 1 ? 'success' : 'error',
        },
        {
          default: () => (row.refer_status === 1 ? '是' : '否'),
        }
      );
    },
  },
  {
    title: '时间',
    key: 'dateTime',
  },
]);

const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '会话详情',
          onClick: handleChatDetail.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
        },
        {
          label: '取消推荐',
          onClick: handleUnRefer.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['refer_del'],
        },
      ],
    });
  },
});

async function handleChatDetail(record: Recordable) {
  if (record.conversationId === formParams.conversationId) {
    handleClose();
  } else {
    Object.assign(formParams, record);
    formParams.loading = true;
    getChatList({ conversationId: record.conversationId}).then(res => {
      formParams.chatList = res.data.list;
      formParams.loading = false;
    })
    isShowDetail.value = true;
    if (leftRow.value === 3) {
      leftRow.value -= 1;
    }
  }
}


function handleDeleteChat(item: any, callback: Function) {
  console.log(item)
  dialog.warning({
    title: '删除问答',
    content: `确定删除本次问答内容吗?删除不影响本次会话其它问答内容`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      deleteConversationChat(item.id).then(res => {
        if (res.code === 200) {
          message.success('删除成功', {
            duration: 1000,
            closable: true,
          });
          if (callback) callback();
        } else {
          message.error(res.message)
        }
      })
    },
    onNegativeClick: () => {
    }
  })
}

function handleClose() {
  isShowDetail.value = false;
  Object.assign(formParams, {
    id: '',
    userId: '',
    dept: '',
    name: '',
    telephone: '',
    conversationId: '',
    feedback: 0,
    refer_status: 0,
    dateTime: '',
    loading: false,
    chatList: []
  });
  if (leftRow.value < 3) {
    leftRow.value += 1;
  }
}

function handleUnRefer(record: Recordable) {
  dialog.warning({
    title: '取消推荐',
    content: `确定将本次对话从推荐会话列表中删除吗?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      delRefer({
        conversationId: record.conversationId
      }).then(res => {
        if (res.code === 200) {
          message.success(res.message)
          reloadPage();
        } else {
          message.error(res.message)
        }
      })
    },
    onNegativeClick: () => {
    }
  })
}

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}
function reloadTable() {
  actionRef.value.reload();
}
function handleSubmit(values: Recordable) {
  actionRef.value.updatePage(1);
}

function handleReset(values: Recordable) {
  Object.assign(searchForm.value, defaultValueRef())
}
</script>

<style lang="less" scoped></style>
